
_ = require 'underscore'
fsp = require '../bin/libs/fs-promises'
Q = require 'q'
path = require 'path'
express = require 'express'

request = require 'request'

# config = require './config-jituan.json'
# config = require './config.json'
config = require './config-xietong.json'
# console.log config
# libs
compilestyl = require('../bin/libs/compile-stylus-single')


# 获取命令行参数
program = require 'commander'
program
  .version('0.0.1')
  .option('-c, --context <context>', 'web app context')
  .option('-p, --project <path>', 'Path for project development.')
  .option('-k, --appkey <key>', 'App Key')
  .option('-o, --override <override>', 'allow project resource override server resource')
  .parse(process.argv)

program.project = program.project or "demo"
context = program.context || ''

console.log "project path: #{program.project} "
console.log "env: #{process.env.NODE_ENV}"


loader = """
//加载模版 js 等

  import "../../../#{program.project}/js/util/import.js"

  export default  {
    getTemplate: function(name){
      if (name) {
        return  require("../../../#{program.project}/js/template/" + name);
      }
    },

    // view contains
    getView: function(name) {

      // return require('./view/' + name);
    },

    getPage: function (name) {
      return require("../../../#{program.project}/js/view/" + name);
    }

  }

"""

#FIXME 应用启动时写loader文件 相对目录 文件静态合并
if process.env.NODE_ENV isnt 'production'
  fsp.writeFile './static/sys/js/loader.js', loader
  .then ->
    console.log 'loader complete'
  .catch ->
    throw new Error 'loader文件写入失败'



module.exports= (app)->

  #及时编译stylus
  app.use "/runtime/css/build.css", compilestyl({src: "#{program.project}/stylus/build.styl", fileName: program.project})




  # 对应runtime.hbs的app.js
  app.get "/app.js", (req, res) ->
    fsp.readFile path.resolve(program.project, 'app.js'), 'utf-8'
    .then (app_js) ->
      res.set('Content-Type', 'application/javascript').send app_js
    .catch (err) ->
      res.status(404).json({message: "app.js not found."})


  # app.get "/sys/js/loader.js", (req, res) ->
  #   console.log 'kkkkkkkkk'
  #   fsp.readFile path.resolve(program.project, 'app.js'), 'utf-8'
  #   .then (app_js) ->
  #     res.set('Content-Type', 'application/javascript').send app_js
  #   .catch (err) ->
  #     res.status(404).json({message: "app.js not found."})

  ###
  # 静态资源
  ###
  # app.use "/images", express.static "#{program.project}/images"
  # app.use "/css", express.static "#{program.project}/css"
  app.use "/fonts", express.static "#{program.project}/fonts"
  # app.use "/sys/js/view", express.static "#{program.project}/js/view"

  # app.use express.static path.resolve '.', 'demo1'

  # 应用手机运行时
  # eg：/apps/:app_id/index.html
  # eg：/index.html （-p {path} 方式启动）
  app.get "/symeetingbook/:page_id.html", (req, res) ->
    code = req.query.code
    qzId = req.query.qzId
    # console.log req.query.appId

    req.session.appId = req.query.appId
    req.session.code = code
    req.session.qzId = qzId
    res.render 'runtime/runtime', {
      # styles: styles
      # app: app_obj
      layout: false,
    }
    # fsp.readdir_safe path.resolve(program.project, "less")
    # .then (styles) ->
    #   # styles是less目录下的文件名列表
    #   # 先过滤出less文件
    #   # 再将后缀转为css，让其匹配后台less即时编译路由
    #   styles = _.chain(styles).filter (file)->
    #     !file.startsWith('_') and file.endsWith('.less') # _开头的不加载
    #   .map (style) ->
    #     style.replace('.less', '.css')
    #   .value()
    #
    #   res.render 'runtime/runtime', {
    #     styles: styles
    #     app: app_obj
    #   }
    # .catch (err) ->
    #   console.trace err
    #   res.status 500

  #openApi获取企业空间用户
  app.get "/symeetingbook/getUser", (req, res) ->
    new Promise (resolve, reject) ->
      request.get "#{config.openApi}", (err, res, body) ->
        return reject(err) if err
        result = JSON.parse(body)
        return reject(err) if result.code != 0
        resolve result
    .then (result) ->
      new Promise (resolve, reject) ->
        token = result.data.access_token
        request.get "#{config.userApi}/#{req.session.code}?access_token=#{token}", (err, res, body) ->
          return reject(err) if err
          result = JSON.parse(body)
          return reject(err) if result.code != 0
          resolve result
    .then (result) ->
      # console.log result
      res.status(200).json {code:0, result: result.data}
    .catch (err) ->
      console.log err if err
      res.status(200).json {code:-1, message: 'err'}


  #推送接口
  app.post "/symeetingbook/meeting/sengMsg", (req, res) ->
    new Promise (resolve, reject) ->
      request.get "#{config.openApi}", (err, res, body) ->
        return reject(err) if err
        result = JSON.parse(body)
        return reject(err) if result.code != 0
        resolve result
    .then (result) ->
      new Promise (resolve, reject) ->
        token = result.data.access_token
        data = {
          spaceId: "#{req.session.qzId}",
          appId: "#{req.session.appId}",
          sendScope:"list",
          sendThrough:"appNotify",
          to:  req.body.to,
          title: req.body.title || "",
          desc: req.body.desc ||  "",
          content: req.body.desc ||  "",
          # detailUrl: req.body.detailUrl ||  "",
        }
        # console.log data
        #FIXME 分享消息暂时
        url = "#{config.appMsg}?access_token=#{token}"
        # console.log url
        options = {
          method: 'post',
          body: data,
          json: true,
          url: url,
        }
        request options, (err, res, body) ->
          # console.log body
          console.log err if err
          return reject(err) if err
          return reject(err) if body.flag != 0
          resolve body
    .then (result) ->
      # console.log result.flag
      res.status(200).json {code:0, result: result.flag}
    .catch (err) ->
      res.status(200).json {code:-1, message: 'err'}
